const http = require('http')
const Router = require('./router')
const methods = require('methods'); // 第三方 因为安装了express ， 我们可以直接用 （幽灵依赖）


const statuses = require('statuses')
const url = require('url')
const mime = require('mime');

function Application() {
    // 这里创建应用后不去使用里有系统
}
Application.prototype.lazy_route = function () {
    if (!this.router) {
        // 没有路由系统再去创建， 还有其他的初始化逻辑

        this.router = new Router;

        this.use(function (req, res, next) {
            let { query, pathname } = url.parse(req.url, true);
            req.query = query;
            req.path = pathname;
            res.sendFile = function (path) {
                res.setHeader('Content-Type', mime.types[path] + ';charset=utf-8')
                require('fs').createReadStream(path).pipe(res);
            }
            res.send = function (value) {
                if (typeof value === 'string' || Buffer.isBuffer(value)) {
                    res.end(value);
                } else if (typeof value === 'number') {
                    res.statusCode = value;
                    res.end(statuses.message[value]);
                } else if (typeof value === 'object') {
                    res.end(JSON.stringify(value))
                }
            }
            next();
        })
    }
}
// 中间件的实现原理
Application.prototype.use = function () {
    this.lazy_route();


    this.router.use(...arguments)
}
methods.forEach(method => {
    Application.prototype[method] = function (path, ...handlers) {
        this.lazy_route();
        this.router[method](path, handlers)
    }
})
Application.prototype.listen = function (...args) {
    const server = http.createServer((req, res) => {
        function done() {
            res.end(`Cannot ${req.method} ${req.url} my`)
        }
        this.lazy_route();
        this.router.handle(req, res, done)
    });



    server.listen(...args);
}
module.exports = Application